
<template>
  <el-form
    :model="form"
    label-width="100px"
    @submit.prevent="submit"
    style="width: 640px"
  >
    <el-form-item label="申请人:" style="width: 400px">
      <el-input v-model="form.userName" disabled></el-input>
    </el-form-item>
    <el-form-item label="部门:" style="width: 400px">
      <el-select v-model="form.depId" placeholder="请选择部门" disabled>
        <el-option label="请选择部门" :value="0"></el-option>
        <el-option label="IT信息部" :value="1"></el-option>
        <el-option label="人力资源部" :value="2"></el-option>
        <el-option label="财务部" :value="3"></el-option>
        <el-option label="销售部" :value="4"></el-option>
        <el-option label="行政部" :value="5"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="请假类别:" style="width: 600px">
      <el-radio-group v-model="form.leaveType">
        <el-radio label="事假" :value="1">事假</el-radio>
        <el-radio label="病假" :value="2">病假</el-radio>
        <el-radio label="婚假" :value="3">婚假</el-radio>
        <el-radio label="丧假" :value="4">丧假</el-radio>
        <el-radio label="产假" :value="5">产假</el-radio>
        <el-radio label="补休" :value="6">补休</el-radio>
        <el-radio label="工伤" :value="7">工伤</el-radio>
        <el-radio label="其他" :value="8">其他</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- 时间选择区域 -->
    <el-form-item label="请假时间：">
      <div>
        <div class="time-range">
          <el-date-picker
            @change="pickerOptionss"
            v-model="form.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm"
            selectableRange="09:00:00 - 17:00:00"
          />
          <span class="time-separator">至</span>
          <el-date-picker
            @change="pickerOptionss"
            v-model="form.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm"
            selectableRange="09:00:00 - 17:00:00"
          />
        </div>
        <div class="duration">共计 {{ duration.totalHours }} 小时</div>
      </div>
    </el-form-item>
    <el-form-item label="总工时">
      <el-input v-model="form.totalhours" autocomplete="off" />
    </el-form-item>

    <el-form-item label="请假事由:" style="width: 400px">
      <el-input v-model="form.reason" type="textarea"></el-input>
    </el-form-item>
    <el-form-item label="部门领导:" style="width: 400px">
      <el-select v-model="form.depheadsName" prop="depheadsName" disabled>
        <el-option
          v-for="item in depuserheads"
          :value="item.userId"
          :label="item.userName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" native-type="submit">提交申请</el-button>
    </el-form-item>
  </el-form>
</template>


<script setup lang="ts">
import axios, { Axios } from "axios";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { onMounted, reactive, ref, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";

import departments from "@/stores/requestDep";
import { en } from "element-plus/es/locales.mjs";

const store = useCounterStore();
// const depStore = depheadsCounterStore();
const router = useRouter();

const form = reactive({
  userName: store.ccstore.userName,
  depId: store.ccstore.depId,
  startTime: "",
  endTime: "",
  leaveType: 0,
  reason: "",
  depheadsName: "",
  applicationId: 0,
  status: 0,
  createTime: new Date(),
  leavetime: "",
  totalhours: 0,
  zongtimeDisplay: "",
});

// 日期选择器的可选时间范围
const pickerOptionss = {
  disabledDate(time: any) {
    return false; // 不限制日期选择
  },
  selectableRange: "09:00:00 - 17:00:00", // 限制可选时间范围为 09:00 到 17:00
};
// 计算请假时长
const duration = computed(() => {
  // 空值保护
  if (!form.startTime || !form.endTime) return { totalHours: 0 };

  // 时间对象转换（考虑Safari兼容性）
  const start = new Date(form.startTime);
  const end = new Date(form.endTime);
console.log(end,'22')
  // 时间差校验
  if (end < start) return { days: 0, hours: 0 }; // 如果结束时间小于开始时间，则返回0
  // 转换为小时（向上取整处理最小请假单位）
  // const totalHours = Math.ceil(diffMs / (1000 * 60 * 60));
  const startDay = start.getDate();

  const endDay = end.getDate();

  const daysDiff = endDay - startDay; //时差
  // alert(daysDiff)
  const startHour = start.getHours();
  // console.log(startHour,"开始")
  const endHour = end.getHours();
  let totalHours = 0;
  if (daysDiff === 0) {
    totalHours = endHour - startHour;
  } else {
    // 第一天剩余工时
    const firstDayHours = 17 - startHour;
    // 中间完整天数工时
    const middleDaysHours = (daysDiff - 1) * 8;
    // 最后一天工时
    const lastDayHours = endHour - 9;
    totalHours = firstDayHours + middleDaysHours + lastDayHours;
    // alert(totalHours)
  }

  form.totalhours = totalHours;
  console.log(totalHours, "总工时");
  const days = Math.floor(totalHours / 8);
  const remainingHours = totalHours % 8; // 按8小时/天计算
  // 按8小时/天计算
  return {
    /* days: days,
    hours: remainingHours, */
    totalHours: form.totalhours,

  };
});

// 日期选择器的可选时间范围
const pickerOptions = {
  disabledDate(time: any) {
    return false; // 不限制日期选择
  },
  selectableRange: "09:00:00 - 17:00:00", // 限制可选时间范围为 09:00 到 17:00
};

onMounted(() => {
  getDepHeads();
});

// 获取部门负责人
const depuserheads = ref<any>([]);
const getDepHeads = () => {
  axios
    .get("https://localhost:7174/api/Message/GetDepHeads/GetDepHeads", {
      params: {
        DepId: store.ccstore.depId,
        Heads: store.ccstore.heads,
      },
    })
    .then((res) => {
      console.log(res.data.data);
      depuserheads.value = res.data.data;
      const leader = depuserheads.value.find((item: any) => item.userName);
      form.depheadsName = leader.userName;
    });
};

// 添加
const submit = () => {
  axios
    .post("https://localhost:7272/api/Message/CreateLeaveApplication", {
      userName: store.ccstore.userName,
      depId: store.ccstore.depId,
      startTime: dayjs(form.startTime).toISOString(),
      endTime: dayjs(form.endTime).toISOString(),
      leaveType: form.leaveType,
      reason: form.reason,
      depheadsName: form.depheadsName,
      applicationId: form.applicationId,
      status: form.status,

      createTime: dayjs(form.createTime).toISOString(),
    })
    .then((res) => {
      console.log(res.data, "dd");
      if (res.data.code === 100) {
        ElMessage.success(res.data.msg);
       
        router.push("/GetLeaveRequestsView");
        return;
      } else {
        ElMessage.success(res.data.msg);
        return;
      }
    });
};
</script>

<style scoped>
</style>